<?php
// +----------------------------------------------------------------------
// | SwiftPHP [ JUST DO ONE THING WELL ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2017  http://swiftphp.zhongwenyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhongwenyu <zhongwenyu1987@163.com> <http://www.zhongwenyu.com>
// +----------------------------------------------------------------------
// | Times: 2017/3/3 21:36
// +----------------------------------------------------------------------
namespace swift;

/*
每段数据以<>间隔
sql调试
['ip'=>'访问ip','time'=>'记录时间','sql'=>'sql语句','runtime'=>'运行时间','path'=>'路由地址']

error出错
['ip'=>'访问ip','time'=>'记录时间','file'=>'出错文件','line'=>'出错行号','message'=>'出错信息','path'=>'路由地址']*/

class Log{
    // 日志信息
    protected static $log = [];
    // 配置参数
    protected static $config = [
        'file_size'   => 2097152,
        'path'        => LOG_PATH,
    ];
    // 日志类型
    protected static $type = ['log', 'error', 'info', 'sql', 'notice', 'alert', 'debug'];
    // 当前日志授权key
    protected static $key;

    /**
     * 检查日志写入权限
     * @param array  $config  当前日志配置参数
     * @return bool
     */
    public static function check($config = [])
    {
        empty(self::$key) && self::$key = Request::instance()->getIp();
        if (!empty($config['allow_key']) && !in_array(self::$key, $config['allow_key'])) {
            return false;
        }
        return true;
    }

    /**
     * 保存日记信息
     * @return bool
     */
    public static function save(array $log , $type = 'log'){
        if(empty($log)) {
            if($type == 'info'){
                $log = ['数据为空！'];
            }else{
                return false;
            }
        }
        $destination = self::$config['path'] . date('Ym') . DS . $type . '-' . date('d') . '.log';
        $path = dirname($destination);
        !is_dir($path) && mkdir($path, 0755, true);
        //检测日志文件大小，超过配置大小则备份日志文件重新生成
        if (is_file($destination) && floor(self::$config['file_size']) <= filesize($destination)) {
            rename($destination, dirname($destination) . DS . $_SERVER['REQUEST_TIME'] . '-' . basename($destination));
        }
        $info = str_replace('<>' , '' , serialize($log)) . '<>';
        return error_log($info, 3, $destination);
    }
}